package com.example.schoolguider.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * @author wjc
 * @date 2023/3/30 21:47
 */
@Configuration
public class MyDataSourceConfig {

    @ConfigurationProperties("spring.datasource")
    @Bean
    public DataSource dataSource() throws SQLException {
        //1. 配置了 @ConfigurationProperties("spring.datasource")
        //   就可以读取到application.yml的配置，注意：我们需要将bean注入到spring ioc容器中、bean中提供get\set方法
        //2. 我们就不需要调用DruidDataSource 对象的setXxx, 会自动关联

        DruidDataSource druidDataSource = new DruidDataSource();

        //配置sql监控
        druidDataSource.setFilters("stat");
        return druidDataSource;
    }
    @Bean
    public ServletRegistrationBean registrationBean(){
        StatViewServlet statViewServlet = new StatViewServlet();
        //配置监控页面的访问路径
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(statViewServlet, "/druid/*");
        //配置登录用户名和密码，结合上面这段 init-param即配置servlet的初始化参数,key和其保持一致，value值我们可以自行定义
        registrationBean.addInitParameter("loginUsername","admin");
        registrationBean.addInitParameter("loginPassword","admin");
        return registrationBean;
    }
    @Bean
    public FilterRegistrationBean webStatFilter(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(webStatFilter);
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        return filterRegistrationBean;
    }
}